package com.googlecode.androidspamblocker;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.telephony.SmsMessage;
import android.util.Log;

public class SmsCustomFilters implements SmsRule {
	private static final String TAG = "SmsCustomFilters";
	private static final String FILTER_DELIMITER = "\n";
	private static final String TYPE_DELIMITER = ",";
	private List<SmsFilter> filters = new LinkedList<SmsFilter>();
	
	public SmsCustomFilters() {
	}
	
	public List<SmsFilter> getFilters() {
		return filters;
	}
	
	public boolean add(SmsFilter filter) {
		return filters.add(filter);
	}
	
	public int match(SmsMessage msg, Context context) {
		Iterator<SmsFilter> iter = filters.iterator();
		while(iter.hasNext()) {
			int action = iter.next().filter(msg, context);
			if(action != SmsAction.UNKNOWN) {
				return action;
			}
		}
		return SmsAction.UNKNOWN;
	}
	
	public int match(SmsMessage[] msg, Context context) {
		Iterator<SmsFilter> iter = filters.iterator();
		while(iter.hasNext()) {
			int action = iter.next().filter(msg, context);
			if(action != SmsAction.UNKNOWN) {
				return action;
			}
		}
		return SmsAction.UNKNOWN;
	}
	
	public void load(String rule) {
		String[] f = rule.split(FILTER_DELIMITER);
		filters.clear();
		Log.d(TAG, "loading rules=" + f.length);
		for (int i = 0; i < f.length; i++) {
			if (f[i].length() > 0) {
				Log.d(TAG, "rule " + i + ": " + f[i]);
				String[] fields = f[i].split(TYPE_DELIMITER, 2);
				SmsFilter filter;
				try {
					filter = (SmsFilter)Class.forName(fields[0]).newInstance();
					filter.load(fields[1]);
					filters.add(filter);
				} catch (IllegalAccessException e) {
					Log.w(TAG, e);
				} catch (InstantiationException e) {
					Log.w(TAG, e);
				} catch (ClassNotFoundException e) {
					Log.w(TAG, e);
				}
			}
		}
	}
	
	public String toString() {
		StringBuilder builder = new StringBuilder();
		Iterator<SmsFilter> iter = filters.iterator();
		while(iter.hasNext()) {
			SmsFilter filter = iter.next();
			builder.append(filter.getClass().getCanonicalName() + TYPE_DELIMITER + filter.toString() + FILTER_DELIMITER);
		}
		return builder.toString();
	}

}
